<?php
/**
 * Created by jinqiang on 2024/6/24 14:19.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Log;


use App\Http\Models\Mysql\SsyJstPurchaseinOrderTable;
use App\Http\Models\Mysql\SsyNewProductsLogTable;
use App\Http\Models\Mysql\SsyPushKingdeeLogTable;
use App\Http\Models\Mysql\SsyPushLmLogTable;
use App\Http\Repository\LinmaoRepository;
use App\Http\Services\Soa\ReturnsService;

class LogService
{
    public function search($param)
    {
        $conn = (new SsyNewProductsLogTable())->where('type_no', $param['type_no'] ?? "")->where('type', (Int)$param['type'])
            ->orderBy("createtime", "desc")
            ->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $conn['data'],
            'total' => $conn['total']
        ];
    }

    public function searchKingdee($param)
    {
        $conn = (new SsyPushKingdeeLogTable());
        if($param['bill_no'] ?? ""){
            $conn = $conn->where('bill_no', 'like', $param['bill_no']."%");
        }
        if($param['type'] ?? ""){
            $conn = $conn->where('type', (Int)$param['type']);
        }
        $res = $conn->orderBy('create_time', "desc")->paginate((Int)$param['limit'])->toArray();
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    public function searchLm($param)
    {
        if(isset($param['status']) && $param['status'] != ""){
            $logs = (new SsyPushLmLogTable())->where('status', (Int)$param['status'])->get(['purchasein_id'])->toArray();
            $param['ids'] = array_column($logs, 'purchasein_id');
            if(empty($logs)){
                return ['data' => [], 'total' => 0];
            }
        }
        $res = (new ReturnsService())->search($param);
        $purchaseinIds = array_column($res['data'], 'id');
        $logList = (new SsyPushLmLogTable())->whereIn('purchasein_id', $purchaseinIds)->get(['purchasein_id', 'data', 'error', 'status'])->toArray();
        $logMap = array_column($logList, null, 'purchasein_id');
        foreach($res['data'] as &$item){
            $item['push_data'] = $logMap[$item['id']]['data'] ?? "";
            $item['push_error'] = $logMap[$item['id']]['error'] ?? "";
            $item['push_status'] = $logMap[$item['id']]['status'] ?? "";
        }
        unset($item);
        return $res;
    }

    public function pushLm($id)
    {
        $purchaseObj = (new SsyJstPurchaseinOrderTable())->where('id', $id)->first()->toArray();
        $res = (new LinmaoRepository())->pushOrder($purchaseObj);
        return $res;
    }
}
